package ss.pku.jsa.type.inference;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import ss.pku.jsa.type.constraint.solver.Native;


public class Profile {
	private static long baseTime = System.currentTimeMillis();
	private static long time = baseTime;
	private static Runtime r = Runtime.getRuntime();
	public static long maxMem = 0L;

	public static void init() {
		maxMem = 0L;
		baseTime = System.currentTimeMillis();
	}

	public static String longToTime(long t) {
		long msecs = t % 1000L;
		long secs = t % 60000L / 1000L;
		long mins = t / 60000L;
		return String.format("%d:%02d.%04d", new Object[] { Long.valueOf(mins),
				Long.valueOf(secs), Long.valueOf(msecs) });
	}

	public static String timestamp() {
		long cur = System.currentTimeMillis();
		long diff = cur - time;
		time = cur;
		return "(" + longToTime(cur - baseTime) + " [+" + longToTime(diff)
				+ "])";
	}

	public static long elapsedTime() {
		return System.currentTimeMillis() - baseTime;
	}

	public static long memoryUsage() {
		long m = r.totalMemory() - r.freeMemory();
		if (m > maxMem)
			maxMem = m;
		return m;
	}

	public static void logMemStart(String msg) {
		if (JqualPlugin.profile) {
			long m = memoryUsage();
			JqualPlugin.out.print("MEM ");
			JqualPlugin.out.print(m);
			JqualPlugin.out.print(" ");
			JqualPlugin.out.println(msg);
		}
	}

	public static void logMemEnd() {
		if (JqualPlugin.profile) {
			long m = memoryUsage();
			JqualPlugin.out.print("END ");
			JqualPlugin.out.println(m);
		}
	}

	public static void logTimeStart(String msg) {
		if (JqualPlugin.profile) {
			long t = elapsedTime();
			JqualPlugin.out.print("TIME ");
			JqualPlugin.out.print(t);
			JqualPlugin.out.print(" ");
			JqualPlugin.out.println(msg);
		}
	}

	public static void logTimeEnd() {
		if (JqualPlugin.profile) {
			long t = elapsedTime();
			JqualPlugin.out.print("ENDTIME ");
			JqualPlugin.out.println(t);
		}
	}

	public static long procMemoryKB() {
		long pid = Native.getpid();
		try {
			Process p = r.exec("ps -p " + pid + " -o vsz");
			BufferedReader ps = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			ps.readLine();
			String vsz = ps.readLine();
			return Long.parseLong(vsz.trim());
		} catch (IOException localIOException) {
		}
		return 0L;
	}

	public static void logStart(String msg) {
		if (JqualPlugin.profile) {
			logMemStart(msg);
			logTimeStart(msg);
		}
	}

	public static void logEnd() {
		if (JqualPlugin.profile) {
			logMemEnd();
			logTimeEnd();
		}
	}
}
